﻿using Microsoft.Extensions.Logging;
using NetCore.Common.Helper;
using NetCore.Common.Quartz.Monitor;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;

namespace NetCore.Common.Quartz
{
    public class QuartzStartup
    {
        public IScheduler _scheduler { get; set; }

        private readonly ILogger<SimpleJobFactory> _logger;
        private readonly IJobFactory iocJobfactory;
        public QuartzStartup(IServiceProvider IocContainer, ILogger<SimpleJobFactory> logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger)); // <-添加此行;
            iocJobfactory = new IOCJobFactory(IocContainer);
            var schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler().Result;
            _scheduler.JobFactory = iocJobfactory;
        }
        // Quartz.Net启动后注册job和trigger
        public void Start()
        {
            _logger.LogInformation("Schedule job load as application start.(启动调度)");
            _scheduler.Start().Wait();

            #region 创建本机CPU监控任务

            //创建任务
            var cpuMonitorJob = JobBuilder.Create<CpuMonitorJob>()
               .WithIdentity("CpuMonitorJob")
               .Build();

            //创建一个触发器
            var cpuMonitorJobTrigger = TriggerBuilder.Create()
                 .WithSimpleSchedule(x => x.WithIntervalInSeconds(AppSettings.Interval_TaskScheduling).RepeatForever())//每两秒执行一次
                .Build();

            //将给定的Quartz.IJobDetail添加到调度程序，并关联给定的Quartz.ITrigger
            _scheduler.ScheduleJob(cpuMonitorJob, cpuMonitorJobTrigger).Wait();

            //触发已识别的Quartz.IJobDetail（立即执行）。
            //_scheduler.TriggerJob(new JobKey("UsageCounterSyncJob"));

            #endregion
        }
    }
}
